/**
 * Copyright (c) 2016 coderyuan.com. All Rights Reserved.
 *
 * EShop
 *
 * HashUtil.java created on 下午5:31
 *
 * @author yuanguozheng
 * @version 1.0.0
 * @since 16/3/2
 */
package com.coderyuan.web.api.kit.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;

/**
 * HashUtil
 *
 * @author yuanguozheng
 */
public class HashUtil {

    public static String getSHA1(String str) {
        return baseHash(str, "SHA-1");
    }

    public static String getSHA1(byte[] data) {
        return baseHash(data, "SHA-1");
    }

    public static String getSHA256(String str) {
        return baseHash(str, "SHA-256");
    }

    public static String getSHA256(byte[] data) {
        return baseHash(data, "SHA-256");
    }

    public static String getMD5(byte[] data) {
        return baseHash(data, "MD5");
    }

    public static String getMD5(String str) {
        return baseHash(str, "MD5");
    }

    private static String baseHash(String str, String algorithm) {
        try {
            return baseHash(str.getBytes("utf-8"), algorithm);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String baseHash(byte[] data, String algorithm) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance(algorithm);
            byte[] hash = digest.digest(data);
            return Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
